<?php

class Admin_UsersController extends Admin_Controller_Base {

   public function indexAction() {
      // this is the list action
      // get the data from the database and use the paginator
      $usersModel = new Model_User();
      $users = $usersModel->fetchAll();
      $this->view->users = $users;
      $this->_setTitle('Users - List');
      $this->_setPaginator('users');
   }

   public function addAction() {
      $this->_setTitle('Users - Add');
      $form = new Admin_Form_Users(array('params' => $this->getRequest()->getParams()));
      $this->view->form = $form;
      
      if($this->getRequest()->isPost()) {
         if($form->isValid($this->_request->getPost())) {
            $user = new Model_User();
            foreach($user->getFields() as $field) {
               $value = trim($form->$field->getValue());
               if($value) {
                  $user->$field = $value;
               }
            }
            $user->id = null;
            $user->insert();
            $this->_redirect("/admin/users");
         }

      }
   }
   
   public function editAction() {
      $this->_setTitle('Users - Edit');
      $form = new Admin_Form_Users(array('params' => $this->getRequest()->getParams()));
      $this->view->form = $form;
      
      if($this->getRequest()->isPost()) {
         if($form->isValid($this->_request->getPost())) {
            $user = new Model_User();
            foreach($user->getFields() as $field) {
               $value = trim($form->$field->getValue());
               if($value) {
                  $user->$field = $value;
               }
            }
            $user->update();
            $this->_redirect("/admin/users");
         }

      }
   }
   
   public function deleteAction() {
      $this->_setTitle('Users - Delete');
      $params = $this->getRequest()->getParams();
      $user = new Model_User();
      $user->id = $params['id'];
      $user->delete();
      $this->_redirect("/admin/users");
   }

}
